package com.mycontact.client;

import com.google.gwt.activity.shared.ActivityManager;
import com.google.gwt.activity.shared.ActivityMapper;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.place.shared.PlaceHistoryHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.mycontact.client.mapper.AppPlaceHistoryMapper;
import com.mycontact.client.mapper.MainPanelActivityMapper;
import com.mycontact.client.place.ViewContactsPlace;
import com.mycontact.client.ui.OneWidgetLayoutPanel;
import com.mycontact.client.ui.TopPanel;

public class Mycontact implements EntryPoint {
interface Binder extends UiBinder<DockLayoutPanel, Mycontact> { }
	
	private static final Binder binder = GWT.create(Binder.class);
	
	@UiField TopPanel topPanel;
	@UiField OneWidgetLayoutPanel mainPanel;
	
	private Place defaultPlace = new ViewContactsPlace();

	public void onModuleLoad() {
		// Create app layout
	    DockLayoutPanel outer = binder.createAndBindUi(this);
	    
	    // Create ClientFactory using deferred binding so we can replace with different
		// impls in gwt.xml
		ClientFactory clientFactory = GWT.create(ClientFactory.class);
		EventBus eventBus = clientFactory.getEventBus();
		PlaceController placeController = clientFactory.getPlaceController();
		
		// Initialize RequestFactory
		clientFactory.initializeRequestFactory();
		
		// Start ActivityManager for each area with its ActivityMapper
		ActivityMapper mainPanelActivityMapper = new MainPanelActivityMapper(clientFactory);
		ActivityManager mainPanelActivityManager = new ActivityManager(mainPanelActivityMapper, eventBus);
		mainPanelActivityManager.setDisplay(mainPanel);
		
		// Start PlaceHistoryHandler with our PlaceHistoryMapper
		AppPlaceHistoryMapper historyMapper= GWT.create(AppPlaceHistoryMapper.class);
		PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(historyMapper);
		historyHandler.register(placeController, eventBus, defaultPlace);
		
		// Set ClientFactory to main toolbar
		topPanel.setClientFactory(clientFactory);
	    
	    // Add app layout to root layout
	    RootLayoutPanel.get().add(outer);
	    
	    // Goes to place represented on URL or default place
		historyHandler.handleCurrentHistory();
	}
}
